#include "watchdog/SyncStatusTask.h"
#include "watchdog/LogWorkItem.h"

#include "common/comm/TaskManager.h"
#include "common/comm/Error.h"
#include "common/sys/ThreadPoolDispatcher.h"
#include "common/comm/AgentManager.h"

#include <iostream>
using namespace std;

extern ThreadPoolDispatcher* g_pDispatcher;

SyncStatusTask::SyncStatusTask():state_(1){}

SyncStatusTask::~SyncStatusTask(){}

int SyncStatusTask::goNext(){
    switch(state_){
        case WATCHDOG_INIT:
            // TODO:需要初始化的内容

            // 初始化完毕后，将状态改为WATCHDOG_SENDING
            state_ = WATCHDOG_SENDING;
            goNext();
            break;
        case WATCHDOG_SENDING:
            // TODO:向其他watchdog节点同步状态

            // 发送完毕后，将状态改为WATCHDOG_WAITING
            state_ = WATCHDOG_WAITING;
            goNext();
            break;
        case WATCHDOG_WAITING:
            // 等待其他watchdog节点返回确认信息
            // TODO:确认后相关后续处理

            // 确认完毕后，将状态改为WATCHDOG_FINISH
            state_ = WATCHDOG_FINISH;
            goNext();
            break;
        case WATCHDOG_RECORDING:
            // TODO:follower收到leader的同步消息后，开始同步状态

            // 同步完成后，将状态改为WATCHDOG_ACK
            state_ = WATCHDOG_ACK;
            goNext();
            break;
        case WATCHDOG_ACK:
            // TODO:follower返回确认消息

            // 返回ack后，将状态改为WATCHDOG_FINISH
            state_ = WATCHDOG_FINISH;
            goNext();
            break;
        case WATCHDOG_FINISH:
            // TODO:状态同步完成后的处理
            // TaskManager::getInstance()->recycle(getID());
            break;
        default:
            break;
    }
    return SUCCESSFUL;
}

void SyncStatusTask::recvWorkItem( ThreadPoolWorkItem* pWorkItem){
    if ( pWorkItem != NULL){
        delete pWorkItem;
        pWorkItem = NULL;
    }
    cout << "this is logWorkitem back" << endl;
    state_ = WATCHDOG_FINISH;
    goNext();
}

void SyncStatusTask::setData(const std::string &data){
    data_ = data;
}